import React from 'react';
import { ColumnProps } from 'antd/lib/table';
import { Select, Input, InputNumber } from 'antd';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import _ from 'lodash';
import md5 from 'blueimp-md5';
import {
  StateType,
  toRepairStatus,
  toMerchantStatus,
  checkShowOpt,
  toPaymentType,
  toUserType,
  getStyle,
  urlEncode,
} from '../utils';
import * as tools from '@/utils/tools';
import { REPAIR_STATUS, RECHARGE_TRANSFER_TYPE_NAMES } from '../data';
import styles from './style.less';
import { checkPermission } from '@/utils/resolvePermission';
import { getLogin } from '@/utils/auth';

const { Option } = Select;

interface SignParamsType {
  device_id?: string;
  os_type?: number;
  timestamp?: number;
  version?: string;
  token?: string | undefined;
  uid?: string | undefined;
  sign?: string;
}

// 充值方式的转换
// 用户状态的转换
export function toRechargeType(val: number): string {
  const obj = _.find(RECHARGE_TRANSFER_TYPE_NAMES, item => item.value === val);
  return obj ? obj.title : '';
}

export function spliceStr(list: any[], value: any) {
  const index = _.findIndex(list, (item: object) => item === value);
  list.splice(index, 1);
}

export function addSign(): object {
  const timestamp = Date.parse(new Date().toString());
  const signParams: SignParamsType = {};
  const { token, uid } = getLogin();
  signParams.device_id = '1.0';
  signParams.os_type = 0;
  signParams.timestamp = timestamp;
  signParams.version = '1.0';
  const urlStr = urlEncode(signParams).substr(1);
  signParams.token = token;
  signParams.uid = uid;
  signParams.sign = md5(`${urlStr}global`);

  return signParams;
}

// 补单操作 -- 列数据
export const getRepairColumns = (self: any) => {
  // 1 全部 2 已补单
  const orderStatusValue = self.props.form.getFieldValue('repairStatus');

  const orderFilterData =
    orderStatusValue === 1
      ? REPAIR_STATUS
      : REPAIR_STATUS.filter((item: { value: string }) => ['2', '3', '4'].includes(item.value));
  const { orderStatus, userType } = self.state.tableFilters;
  const userTypeData = userType ? [userType] : ['-1'];

  let orderStatusData: any[];
  if (typeof orderStatus === 'string') {
    orderStatusData = orderStatus.split(',');
  } else {
    orderStatusData = orderStatus;
  }

  const columns: ColumnProps<StateType>[] = [
    // 充值时间
    {
      title: formatMessage({ id: 'recharge-repair-table.recharge-time' }),
      dataIndex: 'createDate',
      key: 'createDate',
      render: text => tools.toTime(text),
      width: 120,
    },
    // 充值单号
    {
      title: formatMessage({ id: 'recharge-repair-table.order-id' }),
      dataIndex: 'orderId',
      width: 220,
    },
    // 充值金额
    {
      title: formatMessage({ id: 'recharge-repair-table.recharge-amount' }),
      dataIndex: 'amount',
      key: 'amount',
      render: text => tools.currency(text),
      width: 130,
    },
    // 到账金额
    {
      title: formatMessage({ id: 'recharge-repair-table.arrival-amount' }),
      dataIndex: 'payAmount',
      key: 'payAmount',
      width: 130,
      render: (text, record) => {
        // let val = 0;
        // const { status, subStatus } = record;
        // if (status === 3 || subStatus === 2)
        const val = record.status === 3 ? tools.currency(record.amount) : tools.currency(text);
        return val;
      },
    },
    // 账户名
    {
      title: formatMessage({ id: 'recharge-repair-table.account-name' }),
      dataIndex: 'username',
      key: 'username',
      width: 90,
    },
    // 账户类型
    {
      title: '账户类型',
      dataIndex: 'userType',
      key: 'userType',
      width: 110,
      render: text => toUserType(text),
      filters: [
        { text: '全部', value: '-1' },
        { text: '会员', value: '0' },
        { text: '代理', value: '1' },
      ],
      filteredValue: userTypeData,
      filterMultiple: false,
    },
    // 姓名
    {
      title: formatMessage({ id: 'recharge-repair-table.really-name' }),
      dataIndex: 'reallyName',
      key: 'reallyName',
      width: 90,
    },
    // 订单状态
    {
      title: formatMessage({ id: 'recharge-repair-table.order-status' }),
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: 110,
      render: (text, record) => (
        <span style={getStyle(record.status, record.subStatus)}>{toRepairStatus(record)}</span>
      ),
      filters: orderFilterData,
      // filterMultiple: false,
      filteredValue: orderStatusData,
    },
    // 充值方式
    {
      title: '充值方式',
      dataIndex: 'paymentId',
      key: 'paymentId',
      width: 90,
      render: text => toPaymentType(text),
    },
    // 充值商户
    {
      title: formatMessage({ id: 'recharge-repair-table.recharge-merchant' }),
      dataIndex: 'channelId',
      key: 'channelId',
      width: 110,
      render: (text, record) => record.merchantName,
    },
    // 收款人姓名
    {
      title: formatMessage({ id: 'recharge-repair-table.card-name' }),
      dataIndex: 'cardUsername',
      key: 'cardUsername',
      width: 120,
      ...self.getColumnSearchProps('cardUsername'),
    },
    // 收款人银行名称
    {
      title: formatMessage({ id: 'recharge-repair-table.card-bank' }),
      dataIndex: 'bankName',
      key: 'bankName',
      width: 140,
    },
    // 补单金额
    {
      title: formatMessage({ id: 'recharge-repair-table.repair-amount' }),
      dataIndex: 'sucReqAmount',
      key: 'sucReqAmount',
      render: text => tools.currency(text),
      width: 130,
    },
    // 补单时间
    {
      title: formatMessage({ id: 'recharge-repair-table.repair-time' }),
      dataIndex: 'sucReqTime',
      key: 'sucReqTime',
      render: text => tools.toTime(text),
      width: 120,
    },
    // 补单发起人
    {
      title: formatMessage({ id: 'recharge-repair-table.operator' }),
      dataIndex: 'sucReqOperator',
      key: 'sucReqOperator',
    },
    // 操作
    {
      title: formatMessage({ id: 'recharge-repair-table.operation' }),
      dataIndex: 'detail',
      width: 80,
      fixed: 'right',
      render: (text, record) => {
        const element = checkShowOpt(record) ? (
          // 补单
          <span className={styles.tableBtn} onClick={() => self.handleDetail(record)}>
            {formatMessage({ id: 'recharge-repair-table.repair' })}
          </span>
        ) : (
          // 详情
          <span
            className={styles.tableBtn}
            onClick={() => self.setState({ rowData: record, detailDialogVisible: true })}
          >
            {formatMessage({ id: 'recharge-repair-table.detail' })}
          </span>
        );
        return checkPermission(self.props.btns, 'new-finance-recharge-repair-replacement')
          ? element
          : null;
      },
    },
  ];
  return columns;
};

// 充值补单 - 创建单号
export const getCreateColumns = (self: any, bankList: any[], getInfo: Function) => {
  const columns: ColumnProps<StateType>[] = [
    // 关联单号
    {
      title: () => (
        <div>
          <span style={{ color: 'red' }}>*</span>
          <FormattedMessage id="recharge-repair-create-dialog-table.relation-id" />
        </div>
      ),
      dataIndex: 'ord',
      width: 250,
      render: () => (
        // 请输入关联单号
        <Input
          style={{ width: '100%' }}
          placeholder={formatMessage({
            id: 'recharge-repair-create-dialog-table.relation-id-placeholder',
          })}
          onPressEnter={(e: any) => {
            if (e.target.value.trim()) getInfo();
          }}
          onChange={(e: any) => {
            const orderId = e.target.value.trim();
            self.setState({ inputOrderId: orderId });
          }}
          onBlur={(e: any) => {
            if (e.target.value) getInfo();
          }}
        />
      ),
    },
    // 充值方式
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.recharge-type' }),
      dataIndex: 'paymentId',
      key: 'paymentId',
      width: 100,
      render: text => toRechargeType(text),
    },
    // 充值通道
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.recharge-channel' }),
      dataIndex: 'channelName',
      key: 'channelName',
      width: 90,
    },
    // 商户号
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.merchant-code' }),
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      width: 150,
      render: text => (
        <span style={{ width: '140px', wordBreak: 'break-all', textAlign: 'center' }}>{text}</span>
      ),
    },
    // 订单金额
    {
      title: () => (
        <div>
          <span style={{ color: 'red' }}>*</span>
          <FormattedMessage id="recharge-repair-create-dialog-table.order-amount" />
        </div>
      ),
      dataIndex: 'amount',
      key: 'amount',
      width: 150,
      render: () => (
        <InputNumber
          style={{ width: '100%' }}
          min={0}
          precision={2}
          onChange={val => {
            self.setState({ inputAmount: val });
          }}
        />
      ),
    },
    // 账户名
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.account-name' }),
      dataIndex: 'username',
      key: 'username',
      width: 90,
    },
    // 收款卡姓名
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.payee-name' }),
      dataIndex: 'cardUsername',
      key: 'cardUsername',
      width: 100,
      // render: () => (
      //   <Input
      //     onChange={(e: any) => {
      //       const obj = { ...recharge };
      //       obj.payeeName = e.target.value;
      //       self.setState({ orderInfo: { ...orderInfo, recharge: { ...obj } } });
      //     }}
      //   />
      // ),
    },
    // 收款卡银行名称
    {
      title: formatMessage({ id: 'recharge-repair-create-dialog-table.payee-bank-name' }),
      dataIndex: 'bankName',
      key: 'bankName',
      width: 130,
      // render: text => (
      //   <Select
      //     defaultValue={text}
      //     style={{ width: 120 }}
      //     onChange={(val: number) => {
      //       const obj = { ...recharge };
      //       obj.payeeBankId = val;
      //       self.setState({ orderInfo: { ...orderInfo, recharge: { ...obj } } });
      //     }}
      //   >
      //     {bankList.map((item: any) => (
      //       <Option key={item.bankId}>{item.bankName}</Option>
      //     ))}
      //   </Select>
      // ),
    },
  ];
  return columns;
};

// 补单操作 -- 详情 -- 系统订单详情列数据
export const getRepairSysColumns = (self: any) => {
  const { bankList } = self.props.recharge.ordinaryAmountData;
  const { bankId } = self.props.data;
  const bankListData = [...bankList];
  if (bankId === 0 || bankId === -1) {
    bankListData.push({ bankId, bankName: '其他' });
  }

  const columns: ColumnProps<StateType>[] = [
    // 充值时间
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.recharge-time' }),
      dataIndex: 'createDate',
      key: 'createDate',
      width: 120,
      render: text => tools.toTime(text),
    },
    // 充值单号
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-id' }),
      key: 'orderId',
      dataIndex: 'orderId',
      width: 120,
    },
    // 状态
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.status' }),
      dataIndex: 'status',
      key: 'status',
      width: 90,
      // render: text => toStatus(text),
      render: (text, record) => toRepairStatus(record),
    },
    // 订单金额
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-amount' }),
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: text => tools.currency(text),
    },
    // 账户名
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.account-name' }),
      dataIndex: 'username',
      key: 'username',
      width: 90,
    },
    // 收款人姓名
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.accept-bank-name' }),
      dataIndex: 'cardUsername',
      key: 'cardUsername',
      width: 90,
      render: (text, record) => {
        const { channelId } = record;
        return channelId === 1001 || channelId === 1003 ? (
          <Input
            defaultValue={record.cardUsername}
            onChange={(e: any) => {
              self.setState({ payeeName: e.target.value });
            }}
          />
        ) : (
          record.cardUsername
        );
      },
    },
    // 收款银行名称
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.payee-bank-name' }),
      dataIndex: 'bankName',
      key: 'bankName',
      width: 120,
      render: (text, record) => {
        const { bankId: id } = record;
        return record.channelId === 1001 || record.channelId === 1003 ? (
          <Select
            style={{ width: '110px' }}
            defaultValue={id}
            onChange={(val: number) => {
              self.setState({ payeeBankId: val });
            }}
          >
            {bankListData.map((item: any) => (
              <Option value={item.bankId} key={item.bankId}>
                {item.bankName}
              </Option>
            ))}
          </Select>
        ) : (
          record.bankName
        );
      },
    },
    // 补单金额
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.make-up-amout' }),
      key: 'makeUpAmount',
      width: 140,
      render: (text, record) => (
        <InputNumber
          min={0}
          style={{ width: '140px' }}
          value={self.state.saveData.amount}
          disabled={!checkShowOpt(record)}
          onChange={val => {
            const saveData = { ...self.state.saveData, amount: val };
            self.setState({ saveData });
          }}
        />
      ),
    },
  ];
  return columns;
};

// 补单操作 -- 详情 -- 第三方订单详情列数据
export const getRepairMerColumns = (self: any) => {
  const { data } = self.props;
  const columns: ColumnProps<StateType>[] = [
    // 入款商户
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.accept-merchant' }),
      dataIndex: 'channelName',
      key: 'channelName',
      render: (text, record) => `${record.channelName || ''} ${record.merchantCode || ''}`,
    },
    // 订单时间
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-time' }),
      dataIndex: 'payDate',
      key: 'payDate',
      render: text => tools.toTime(text),
    },
    // 订单单号
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-code' }),
      dataIndex: 'thirdOrderId',
      key: 'thirdOrderId',
    },
    // 订单状态
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-status' }),
      dataIndex: 'status',
      key: 'status',
      render: text => toMerchantStatus(text),
    },
    // 订单金额
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.order-amount' }),
      dataIndex: 'amount',
      key: 'amount',
      render: text => tools.currency(text),
    },
    // 姓名
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.really-name' }),
      dataIndex: 'name',
      key: 'name',
    },
    // 操作
    {
      title: formatMessage({ id: 'recharge-repair-detail-dialog-table.operation' }),
      dataIndex: 'opt',
      key: 'opt',
      render: () => {
        const element = checkShowOpt(data) ? (
          // 验证订单状态
          <span className={styles.btnLine} onClick={() => self.handleCheck(data)}>
            {formatMessage({ id: 'recharge-repair-detail-dialog-table.check-status' })}
          </span>
        ) : null;
        return element;
      },
    },
  ];
  return columns;
};

export const getRelationColumns = () => {
  const columns: ColumnProps<StateType>[] = [
    // 订单号
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
    },
    // 充值方式
    {
      title: '充值方式',
      dataIndex: 'channelName',
      key: 'channelName',
    },
    // 充值通道
    {
      title: '充值通道',
      dataIndex: 'channelId',
      key: 'channelId',
    },
    // 商户号
    {
      title: '商户号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      width: 150,
      render: text => (
        <span style={{ width: '140px', wordBreak: 'break-all', textAlign: 'center' }}>{text}</span>
      ),
    },
    // 订单金额
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      render: text => tools.currency(text),
    },
    // 账户名
    {
      title: '账户名',
      dataIndex: 'userName',
      key: 'userName',
    },
    // 收款卡姓名
    {
      title: '收款卡姓名',
      dataIndex: 'cardUsername',
      key: 'cardUsername',
    },
    // 收款卡银行
    {
      title: '收款卡银行',
      dataIndex: 'bankName',
      key: 'bankName',
    },
    // 订单状态
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
    },
  ];

  return columns;
};
